lightOneButton("al")

/**
 * 左下角产业链党建内容切换
 * @param flag
 */

function switchText(flag) {
    if (flag) {
        $(".cyl-dzz-zf-qys p").text("产业链党组织")
        $(".cyl-dzz").removeClass("hide")
        $(".zf-qys").addClass("hide")

        $(".cyl-tg").removeClass("hide")
        $(".cyl-tg-diqu").addClass("hide")

    } else {
        $(".cyl-dzz-zf-qys p").text("走访企业数统计")
        $(".zf-qys").removeClass("hide")
        $(".cyl-dzz").addClass("hide")

        $(".cyl-tg-diqu").removeClass("hide")
        $(".cyl-tg").addClass("hide")

    }
    // changeNum()
}


$('.xq-tag-box').on('click', 'div', function (event) {
    // 获取点击事件的目标元素
    var clickedElement = event.target;
    // 获取元素的类名
    var id = clickedElement.id;
    if (id.slice(0, 2) === currentDiqu) {
        id = 'al'
    }
    // 输出类名
    lightOneButton(id)
    choseDiqu('diqu-' + id)
    getRefreshTable()

})

/**
 *点击底部地区列表 展开开关
 */

$("#bottom-diqu").on("click", function () {
    if ($(".bg_clicked").length === 0) {
        $("#bottom-diqu").addClass("bg_clicked");

        $.each((diqu), function (index, item) {
            let template = ''
            if (index == currentDiqu) {
                template = '<li id="diqu-?" class="diqu-dialog-li selected-diqu">?</li>'
            } else {
                template = '<li id="diqu-?" class="diqu-dialog-li">?</li>'
            }
            template = template.format(index, item);
            $(".diqu-dialog-ol").append(template);
        })
        $(".diqu-dialog").removeClass("hide");
    } else {
        $(".diqu-dialog-ol").empty();
        $("#bottom-diqu").removeClass("bg_clicked");
        $(".diqu-dialog").addClass("hide");

    }

});

/**
 *点击底部地区列表
 */
$(".diqu-dialog-ol").on("click", "li", function (event) {
    // 获取点击事件的目标元素
    var clickedElement = event.target;
    // 获取元素的类名
    var id = clickedElement.id;
    choseDiqu(id)
    lightOneButton(id.slice(-2))
    getRefreshTable()

})


/**
 * 地区列表切换
 * @param id
 */
function choseDiqu(id) {
    $(".selected-diqu").removeClass("selected-diqu");
    $("#" + id).addClass("selected-diqu");
}

/**
 * 切换地图选中的点
 * @param id
 */

/*
* 是否为首次切换到首页
* */

function lightOneButton(id) {
    if (id === 'al') {
        $.each($('.xq-tag-box > div '), function (index, item) {
            $("#" + item.className).removeClass("hide")
            $("#" + item.className + "01").addClass("hide")
            $("#" + item.className).css({
                'opacity': '1'
            });
        })
        $(".img-map").attr("src", "images/wx.png")
        $("#bottom-diqu").text(diqu['al'])
        currentDiqu = 'al';
        switchText(true)
        if (noFirst) {
            changeCharts("#single-date", "param", "al")
            changeChart("#dg-chart-4", "LOCATION_code", "al")
        }
        noFirst = true
        cengji=0
        /*产业链统计切换到整体（左下角内容）*/
        /*cardDiquController(true)*/
    } else {
        $.each($('.xq-tag-box > div '), function (index, item) {
            if (item.className === id.slice(0, 2)) {
                $("#" + item.className).addClass("hide")
                $("#" + item.className + "01").removeClass("hide")
                $(".img-map").attr("src", "images/" + item.className + ".png")
                $("#bottom-diqu").text(diqu[item.className])
                currentDiqu = item.className;
            } else {
                $("#" + item.className).removeClass("hide")
                $("#" + item.className + "01").addClass("hide")
                $("#" + item.className).css({
                    'opacity': '0.5'
                });
            }
        })
        switchText()
        /*产业链统计切换到地区（左上角内容）*/
        cardDiquController()
        changeChart("#cyl-tg-diqu-chart", "LOCATION_code", currentDiqu.toUpperCase())

        /*数据组*/
        changeCharts("#single-date", "param", currentDiqu.toUpperCase())
        /*活动开展情况*/
        changeChart("#dg-chart-4", "LOCATION_code", currentDiqu.toUpperCase())
    }


}

/**
 * 左上角状态切换、
 * 传入false 切换到卡片
 * @param flag
 */

function cardDiquController(flag) {
    if (flag) {
        $(".cyl-tg-diqu-img").removeClass("hide")
        $(".cyl-tg-diqu-table").removeClass("hide")
        $(".cyl-tg-diqu-list").addClass("hide")
        cengji=2
    } else {
        cengji=1
        $(".cyl-tg-diqu-img").addClass("hide")
        $(".cyl-tg-diqu-table").addClass("hide")
        $(".cyl-tg-diqu-list").removeClass("hide")
    }
    console.log(cengji)
}

function selectDangzuzhi(chartEvent) {
    /*数据组*/
    let active = chartEvent.originalData
    current_dangzuzhi = active.ID
    changeCharts("#single-date", "param", active.ID)
    changeChart("#dg-chart-4", "LOCATION_code", active.ID)

    populateTableWithImages(active)
    cardDiquController(true)
    getRefreshTable()
}

/*左下角产业链党组织点击单独项目-切换地区*/
function selectDiqu(chartEvent) {
    choseDiqu("diqu-" + chartEvent.originalData.LOCATION.toLowerCase())
    lightOneButton(chartEvent.originalData.LOCATION.toLowerCase())
    let active = chartEvent.originalData
    current_dangzuzhi = active.ID

    populateTableWithImages(active)
    cardDiquController(true)
    getRefreshTable()
}

function populateTableWithImages(active) {
    // Parse the PHOTO array (handling both string and array formats)
    let photos = [];
    try {
        photos = typeof active.PHOTO === 'string' ? JSON.parse(active.PHOTO) : active.PHOTO;
    } catch (e) {
        console.error("Error parsing PHOTO data:", e);
        photos = [];
    }
    // Generate HTML for each image
    let photosHtml = '';
    if (photos.length > 0) {
        photos.forEach(photo => {
            const cleanPhoto = photo.replace(/["'\[\]]/g, '');
            const imageUrl = `https://www.wxxf.net.cn/zhdj-api/zhdj/userfiles/fileupload/${cleanPhoto}`;
            photosHtml += `
                <div class="photo-item" style="flex: 0 0 auto; margin-right: 15px;">
                    <img src="${imageUrl}" alt="产业链活动照片" style="height: 100%; width: auto; max-width: none;">
                </div>`;
        });
    } else {
        photosHtml = '<div>暂无活动照片</div>';
    }

    // Set the table HTML with all images
    $(".cyl-tg-diqu-table").html(`
        <div class="title">${active.PARTY_NAME || '宜兴市节能环保产业链党委'}</div>
        <div class="table_active scrollbar-y">
            <table>
                <tr>
                    <td class="td_left">所属层级</td>
                    <td class="td_right">${active.LEVEL || ''}</td>
                </tr>
                <tr>
                    <td class="td_left">成立时间</td>
                    <td class="td_right">${active.FORMATTED_DATE || ''}</td>
                </tr>
                <tr>
                    <td class="td_left">理事长或书记</td>
                    <td class="td_right">${active.COMBINED_PRINCIPAL || ''}</td>
                </tr>
                <tr>
                    <td class="td_left">产业链简介</td>
                    <td class="td_right">${active.CONTENT || '暂无简介'}</td>
                </tr>
                <tr>
                    <td class="td_left">产业链活动</td>
                    <td class="td_right" >
                        <div class="photo-container scrollbar-x"  >
                            ${photosHtml}
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    `);
}


function changeCharts(elem, name, mdata) {
    var loadchart = $(elem)
    if (dashboard.renderedChart(loadchart)) {
        var chart01 = dashboard.chartOf(loadchart);
        chart01.dataSetParamValue(0, name, mdata);
        chart01.dataSetParamValue(1, name, mdata);
        chart01.dataSetParamValue(2, name, mdata);
        chart01.dataSetParamValue(3, name, mdata);
        chart01.dataSetParamValue(4, name, mdata);
        chart01.refreshData();
        chart01.resize()
    }
}

function changeChart(elem, name, mdata) {
    var loadchart = $(elem)
    if (dashboard.renderedChart(loadchart)) {
        var chart01 = dashboard.chartOf(loadchart);
        chart01.dataSetParamValue(0, name, mdata);
        chart01.refreshData();
        chart01.resize( )
    }
}

/**
 * 切换各地区的统计数据
 */

var singleDateListener = {
    onUpdate: function (chart, results) {
        changeNum(results)
    }
}

function changeNum(results) {
    let title_list = ["qiye-number-1", "qiye-number-2", "qiye-number-3", "qiye-number-4", "qiye-number-5", "qiye-number-6"]

    let title_list2 = ["dangzuzhi-number-1", "dangzuzhi-number-2", "dangzuzhi-number-3", "dangzuzhi-number-4"]
    let title_list3 = ["fl-fg-b-content-1", "fl-fg-b-content-2", "fl-fg-b-content-3", "fl-fg-b-content-4"]
    let title_list4 = ["fl-fg-g-content-1", "fl-fg-g-content-2", "fl-fg-g-content-3", "fl-fg-g-content-4"]


    let funeng = results[0] //产业链党建-赋能发展情况_yj
    let yuedu = results[1] //产业链党建-赋能发展情况月度表_yj
    let dangyuan = results[2] //产业链党建-党员覆盖情况统计_yj
    let sanzhang = results[3] //产业链党建-三张清单统计总数_yj
    let zoufang = results[4] //产业链党建-走访企业总数_yj


    console.log(zoufang)

    if (dangyuan.data.length > 0) {
        $(".fg-dg1").text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_COVERED_ORG_NUM"]))
        $(".fg-dg2").text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_COVERED_MEMBER_NUM"]))
        $(".fg-dg1-text").html("<label>党员数</label>" + formatNumberWithCommas(dangyuan.data[0]["TOTAL_COVERED_MEMBER_NUM"]))
        $(".fg-dg2-text").html("<label>党组织数</label>" + formatNumberWithCommas(dangyuan.data[0]["TOTAL_COVERED_ORG_NUM"]))
        $("." + title_list[0]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_ORG"]))
        $("." + title_list[1]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_COVERED_ENTR_NUM"]))
        $("." + title_list[2]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_UNIVERSITIES_RESEARCH_INSTITUTES"]))
        $("." + title_list[3]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_TRADE_ASSOCIATIONS_CHAMBERS"]))
        $("." + title_list[4]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_NEW_TYPES_INSTITUTIONS"]))
        $("." + title_list[5]).text(formatNumberWithCommas(dangyuan.data[0]["TOTAL_OTHERS"]))
    } else {
        $(".fg-dg1").text("0")
        $(".fg-dg2").text("0")
        $(".fg-dg1-text").html("<label>党员数</label>" + "0")
        $(".fg-dg2-text").html("<label>党组织数</label>" + "0")
        $("." + title_list[0]).text("0")
        $("." + title_list[1]).text("0")
        $("." + title_list[2]).text("0")
        $("." + title_list[3]).text("0")
        $("." + title_list[4]).text("0")
        $("." + title_list[5]).text("0")
    }


    if (sanzhang.data.length > 0) {
        $("." + title_list2[0]).text(formatNumberWithCommas(sanzhang.data[0]["DEMAND_NUM"]))
        $("." + title_list2[1]).text(formatNumberWithCommas(sanzhang.data[0]["RESOURCE_NUM"]))
        $("." + title_list2[2]).text(formatNumberWithCommas(sanzhang.data[0]["PROJECT_NUM"]))
        $("." + title_list2[3]).text(formatNumberWithCommas(sanzhang.data[0]["PROJECT_COMPLETE_NUM"]))
    } else {
        $("." + title_list2[0]).text("0")
        $("." + title_list2[1]).text("0")
        $("." + title_list2[2]).text("0")
        $("." + title_list2[3]).text("0")
    }


    if (funeng.data.length > 0) {
        // 总数
        $("." + title_list3[0]).text(formatNumberWithCommas(funeng.data[0]["TALENT_NUM"]))          //帮助引进人才数(人)
        $("." + title_list3[1]).text(formatNumberWithCommas(funeng.data[0]["PROJECT_NUM"]))         //帮助对接项目数(人)
        $("." + title_list3[2]).text(formatNumberWithCommas(funeng.data[0]["FUND_AMOUNT"]))         //帮助引进资金(万元)
        $("." + title_list3[3]).text(formatNumberWithCommas(funeng.data[0]["TECH_PROJECTS"]))       //帮助技术公关(个)
    } else {
        $("." + title_list3[0]).text("0")          //帮助引进人才数(人)
        $("." + title_list3[1]).text("0")         //帮助对接项目数(人)
        $("." + title_list3[2]).text("0")         //帮助引进资金(万元)
        $("." + title_list3[3]).text("0")       //帮助技术公关(个)
    }


    if (yuedu.data.length > 0) {
        // 当月新增
        $("." + title_list4[0]).text(formatNumberWithCommas(yuedu.data[0]["NEW_TALENT"]))           //帮助引进人才数(人)
        $("." + title_list4[1]).text(formatNumberWithCommas(yuedu.data[0]["NEW_PROJECT"]))          //帮助对接项目数(人)
        $("." + title_list4[2]).text(formatNumberWithCommas(yuedu.data[0]["NEW_FUND"]))             //帮助引进资金(万元)
        $("." + title_list4[3]).text(formatNumberWithCommas(yuedu.data[0]["NEW_TECH_PROJECTS"]))    //帮助技术公关(个)
    } else {
        $("." + title_list4[0]).text("0")           //帮助引进人才数(人)
        $("." + title_list4[1]).text("0")          //帮助对接项目数(人)
        $("." + title_list4[2]).text("0")             //帮助引进资金(万元)
        $("." + title_list4[3]).text("0")    //帮助技术公关(个)
    }
    if (zoufang.data.length > 0) {
        // 当月新增
        $(".zf-qys-title-num" ).text(formatNumberWithCommas(zoufang.data[0]["TOTAL_VISIT_ENTR_NUM"]))           //帮助引进人才数(人)
    } else {
        $(".zf-qys-title-num" ).text("0")           //帮助引进人才数(人)
    }


}


function formatNumberWithCommas(num) {
    return new Intl.NumberFormat('en-US').format(num);
}


